<?php

namespace App\Http\Controllers\V1\BasicData;

use App\Http\Requests\V1\TimetableRequest;
use App\Models\V1\InfoNotice;
use App\Models\V1\NewArrival;
use App\Models\V1\Timetable;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Log;
class TimeTablesController extends Controller
{
    /**
     * 显示班级数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $codes = $this->getEnrollmentCodes();
        $data['codes'] = $codes;
        $arrival_code = $this->getArrivalCodes();
        $data['arrival_code'] = $arrival_code;
        return view('v1.newData.timetable',$data);
    }


    /**
     * 获取生活用品数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的班级数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $arrival_code = $request->get('arrival_code');

        $from_select = $request->get('from_select');

        if ($from_select == false && empty($arrival_code)) {
            $arrival_code = $this->getArrivalCodes();
        }

        // 获取符合查询条件的班级数据
        $data = $this->getTimetableList($currentPage, $rows, $arrival_code);

        if (!$data->isEmpty()) {
            $formatList = array();
            $count = $data->total() > 0 ? $data->total() : 0;
            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['code'] = $item['code'];
                    $formatItem['name'] = $item['name'];
                    $formatItem['category'] = $item['category'];
                    $formatItem['time'] = $item['time'];
                    $formatItem['detail'] = $item['detail'];
                    $formatItem['address'] = $item['address'];
                    $formatItem['reception_person'] = $item['reception_person'];
                    $formatItem['attention'] = $item['attention'];
                    $formatItem['show_order'] = $item['show_order'];
                    $relate_information = $this->formatRelate($item['relate_information']);

                    $formatItem['relate_information'] = $relate_information;
                    $formatItem['arrival_code'] = $item['arrival_code'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }
                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }
        return $response;
    }

    /**
     * 进入单条班级数据显示界面（适用于新增addData、编辑editData、查看viewData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $data['view'] = $request->input('view');
        $data['processes'] = $this->getProcessList();
        switch ($request->input('view')) {
            case 'addData':
                return view('v1.form.timetable_item', $data);
                break;
            case 'viewData':
                $code = $request->input('code');
                $arrival_code = $request->input('arrival_code');
                $timetable = $this->getTimetableByCode($code,$arrival_code);
                $relate_information = $this->formatRelate($timetable['relate_information']);
                if ($relate_information === '添加') {
                    $relate_information = '';
                }
                $timetable['relate_information'] = $relate_information;
                $data['timetable'] = $timetable;
                return view('v1.form.timetable_item', $data);
        }
    }
    
    private function getProcessList() {
        $process_codes = ['process1','process2','process3','process4','process5','process6'];
        $process_names = ['生活用品','新生教材','费用类别','报到流程','校服清单','志愿设置'];
        $formatProcess = array();
        for ($i = 0; $i < count($process_codes); $i++ ) {
            $process = [
                'code' => $process_codes[$i],
                'name' => $process_names[$i],
            ];
            array_push($formatProcess,$process);
        }
        return $formatProcess;
    }

    /***
     * 添加关联
     */
    public function addRelation(Request $request) {
        $code = $request->get('code');
        $arrival_code = $request->get('arrival_code');
        $data['code'] = $code;
        $data['arrival_code'] = $arrival_code;
        $notices = $this->getNoticeList();
        $data['notices'] = $notices;
        return view('v1.newData.timetable_relate',$data);
    }

    public function addRelationData(Request $request) {
        $type = $request->get('type');
        $code = $request->get('code');
        $arrival_code = $request->get('arrival_code');
        $response = [
            'rspStatus' => false,
            'rspMsg' => '迎新日程[' . $code . '],添加关联失败！',
        ];
        $content ='';
        if ($type == 1){
            $content = [
                'type' => $type,
                'noticeCode'=> $request->get('notice_code')
            ];
        }else {
            $content = [
                'type' => $type,
                'name'=> $request->get('name'),
                'url'=> $request->get('url')
            ];
        }
        $updateData = [
            'relate_information' => json_encode($content),
        ];
        $rspObj = Timetable::where('code', $code)
            ->where('arrival_code',$arrival_code)
            ->update($updateData);
        if ($rspObj) {
            $response['rspStatus'] = true;
            $response['rspMsg'] = '迎新日程[' . $code . ']添加关联成功！';
        }
        return $response;
    }

    /**
     * 显示迎新换届数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser->getAttribute('code');

        return view('v1.form.upload_excel', $data);
    }


    /**
     * 新增基本信息
     *bail关键字表示只要第一个验证失败后面就不验了，提高效率
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '迎新日程[' . $request->input('code') . '],新增失败！',
        ];

        if ($request->method() === 'POST') {

            // 验证请求
            $rules['code'] = 'bail|required';
            $rules['name'] = 'bail|required';
            $rules['time'] = 'bail|required';
            $rules['detail'] = 'bail|required';
            $rules['address'] = 'bail|required';
            $rules['captcha'] = 'bail|required|captcha';
            $messages['code.required'] = '现场报到任务代码不能为空';
            $messages['name.required'] = '现场报到任务名称不能为空';
            $messages['time.required'] = '日期不能为空';
            $messages['detail.required'] = '具体时间要求不能为空';
            $messages['address.required'] = '地点不能为空';
            $messages['captcha.required'] = '验证码不能为空';
            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);

            // 新增信息
            $successFlag = $this->handleAdd($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '迎新日程[' . $request->input('code') . '],新增成功！';
            }
        }

        return $response;
    }

    /**
     * 编辑日程
     */
    public function updateData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '迎新代码[' . $request->input('edit_code') . '],更新失败！',
        ];
        
        if ($request->method() === 'POST') {
            
            // 启动学期信息
            $successFlag = $this->handleUpdateData($request);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '迎新代码[' . $request->input('edit_code') . '],更新成功！';
            }
        }
        
        return $response;
    }
    
    /**
     * 执行编辑日程
     */
    public function handleUpdateData($request){
        
        $code = $request->input('edit_code');
        $name = $request->input('edit_name');
        $category = $request->input('edit_category');
        $time = $request->input('edit_time');
        $detail = $request->input('edit_detail');
        $address = $request->input('edit_address');
        $reception_person = $request->input('edit_reception_person');
        $attention = $request->input('edit_attention');
        $relate_information = $request->input('edit_relate_information');
        $created_at = $request->input('edit_created_at');
        $updated_at = $request->input('edit_updated_at');
        
        $successFlag = Timetable::updateOrCreate([
            'code' => $code,
        ],[
            'name' => $name,
            'category' => $category,
            'time' => $time,
            'detail' => $detail,
            'address' => $address,
            'reception_person' => $reception_person,
            'attention' => $attention,
            'relate_infomation' => $relate_information,
            'created_at' => $created_at,
            'updated_at' => $updated_at,
        ]);
        
        if($successFlag){
            return true;
        }else{
            return false;
        }
    }
    
    /**
     * 更新报到流程基本信息(单元格)
     *
     * @param TimetableRequest $request
     * @return array
     */
    public function updateCellData(TimetableRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '日程代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateTimetable($request);

            // 更新部门信息
            $successFlag = $this->handleUpdate($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '日程代码[' . $request->input('code') . '],更新成功！';
            }
        }

        return $response;
    }


    /**
     * 删除班级基本信息
     *
     * @param TimetableRequest $request
     * @return array
     */
    public function deleteData(TimetableRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '日程代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateTimetable($request);

            // 删除班级信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '日程代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除班级基本信息
     *
     * @param Request $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '日程批量删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '日程批量删除成功！';
            }
        }

        return $response;
    }
    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑功能函数
    ///////////////////////////////////////////////////////////////////

    /***
     * 处理添加
     * @param Request $request
     * @return mixed
     */
    public function handleAdd(Request $request) {
        $arrival_code = $this->getArrivalCodes();

        // 拼装新增数据数组
        $insertData = [
            'code' => $request->input('code'),
            'name' => $request->input('name'),
            'category' => $request->input('category'),
            'time' => $request->input('time'),
            'detail' => $request->input('detail'),
            'address' => isset($request['address'])?$request->input('address'):'',
            'reception_person' => isset($request['reception_person'])?$request->input('reception_person'):'',
            'attention' => isset($request['attention'])?$request->input('attention'):'',
            'show_order' => $request->input('show_order'),
            'arrival_code' => $arrival_code,
        ];
        $rspObj = Timetable::updateOrCreate(['code'=>$request->input('code')],$insertData);
        
        return $rspObj;
    }


    /****
     * @param Request $request
     * @param $bCell 是否为单元格修改数据
     * @return mixed
     */
    public function handleUpdate(Request $request, $bCell) {
        $where = $request->input('code');
        $arrival_code = $request->input('arrival_code');
        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组
            $updateData = [
                'name' => $request->input('name'),
                'time' => $request->input('time'),
                'detail' => $request->input('detail'),
                'address' => $request->input('address'),
                'reception_person' => $request->input('reception_person'),
                'attention' => $request->input('attention'),
                'relate_information' => $request->input('relate_information'),
                'show_order' =>  $request->input('show_order'),
            ];
        }

        $rspObj = Timetable::where('code', $where)
            ->where('arrival_code',$arrival_code)
            ->update($updateData);

        return $rspObj;
    }


    /**
     * 处理更新班级信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');
        $arrival_codes = $request->input('arrival_code');
        if ($bBatch) { // 批量删除
            for ($i=0; $i<count($where);$i++) {
                $code = $where[$i];
                $arrival_code = $arrival_codes[$i];
                $rspObj = Timetable::where('code', $code)
                    ->where('arrival_code',$arrival_code)
                    ->delete();
            }
        } else { // 单条删除
            $rspObj = Timetable::where('code', $where)
                ->where('arrival_code',$arrival_codes)
                ->delete();
        }

        return $rspObj;
    }

    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的迎新列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getTimetableList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = Timetable::orderBy('show_order','asc')
                ->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = Timetable::where('arrival_code', 'like', '%' . $keywords . '%')
                ->orderBy('show_order', 'asc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    /***
     * 根据code获取日程信息
     * @param $code
     * @return mixed
     */
    private function getTimetableByCode($code,$arrival_code)
    {
        $major = Timetable::where('code', $code)->where('arrival_code',$arrival_code)->first();
        return $major;
    }

    /***
     * 获取当前的迎新代码
     * @return array
     */
    private function getArrivalCodes()
    {
        $code = '';
        $years = NewArrival::where('isOn',true)->first();
        if (!empty($years) || isset($years)) {
            $code = $years->code;
        }
        return $code;
    }

    /**
     * 获取所有招生年份
     *
     * @param $code
     * @return mixed|string
     */
    private function getEnrollmentCodes()
    {
        $codes = NewArrival::all()->pluck('code')->toArray();
        return $codes;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单请求功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新班级信息验证请求
     *
     * @param Request $request
     */
    private function validateTimetable(Request $request)
    {
        $rules = $request->rules();
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }


    /***
     * 格式化相关信息
     * @param $relate_information
     */
    private function formatRelate($relate_information) {
        if (empty($relate_information)) {
            $result = '添加';
        }else{
            $content = json_decode($relate_information, true);
            $type = $content['type'];
            if ($type == 1) {
                $code = $content['noticeCode'];
                $notice = InfoNotice::where('code',$code)->first();
                if (empty($notice) || !isset($notice)) {
                    $result = $code;
                }else{
                    $result = $notice['title'];
                }
            }else {
                $result = $content['name'];
            }
        }
        return $result;
    }

    /***
     * 获取所有可在移动端显示的公告
     * @param $relate_information
     * @return string
     */
    private function getNoticeList() {
        $notices = InfoNotice::where('isShow',true)->select('code','title')->get();
        return $notices;
    }
}
